﻿using Ldc_VoteSys.Models;
using Ldc_VoteSys.Models.Database;
using Ldc_VoteSys.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ldc_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Ldc_VoteSysContext _db;
        private readonly IJWTService _jwtSetvice;
        public UserController(Ldc_VoteSysContext db,IJWTService jwtService)
        {
            _db = db;
            _jwtSetvice = jwtService;
        }
        //注册
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            if (request.UserPassw != request.QrUserPassw)
            {
                return "密码第二次不正确，请重新输入";
            }
            if (_db.Users.Any(x => x.UserEmail == request.UserEmail))
            {
                return "手机号码重复,请重新输入";
            }
            _db.Users.Add(new User
            {
                CreaTime = DateTime.Now,
                UserEmail=request.UserEmail,
                UserPassw=request.UserPassw,
                UserName=string.Empty,
                UserImg=string.Empty
            });

            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "注册成功";
            }
            return "注册失败";
        }



        //登录
        [HttpPost]
        public string Login(LoginRequest request)
        {
            var user = _db.Users.FirstOrDefault(x => x.UserEmail == request.UserEmail);
            if (user == null)
            {
                return "用户不存在";
            }
            if (user.UserPassw != request.UserPassw)
            {
                return "密码错误";
            }
            //创建token
            return _jwtSetvice.CreateToken(user.UserId, user.UserEmail);
        }
    }
}
